package com.duola.security.distributed.order.dao;

import com.duola.security.distributed.order.model.PermissionDto;
import com.duola.security.distributed.order.model.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * @author shkstart
 * @create 2021-12-28 1:16
 */
@Repository
public class UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 根据用户名查询用户信息
     * @param username
     * @return
     */
    public UserDto getUserByUsername(String username) {
        String sql = "select id,username,password,fullname from t_user where username = ?";
        List<UserDto> list = jdbcTemplate.query(sql, new Object[]{username}, new BeanPropertyRowMapper<>(UserDto.class));
        System.out.println(list);
        if (list == null && list.size() <= 0) {
            return null;
        }
        return list.get(0);
    }

    /**
     * 根据用户的id查询用户的权限
     * @param id
     * @return
     */
    public List<String> findPermissionsByUserId(String id) {
        String sql = "SELECT *  FROM t_permission WHERE id in (\n" +
                "\tSELECT permission_id from t_role_permission WHERE role_id in (\n" +
                "\t\tSELECT role_id FROM t_user_role WHERE user_id =?\n" +
                "\t)\n" +
                "\t\n" +
                ")";
        List<PermissionDto> list = jdbcTemplate.query(sql, new Object[]{id}, new BeanPropertyRowMapper<>(PermissionDto.class));
        System.out.println(list);

        ArrayList<String> permissions = new ArrayList<>();
        list.iterator().forEachRemaining(c ->permissions.add(c.getCode()));
        return permissions;
    }
}
